import { BleManager } from 'react-native-ble-plx';

class BluetoothConnector {
  private manager: BleManager;

  constructor() {
    this.manager = new BleManager();
  }

  async scanDevices() {
    try {
      const subscription = this.manager.onStateChange((state) => {
        if (state === 'PoweredOn') {
          this.manager.startDeviceScan(null, null, (error, device) => {
            if (error) {
              console.error('Scan error:', error);
              return;
            }
            console.log('Found device:', device?.name);
          });
          subscription.remove();
        }
      }, true);
    } catch (error) {
      console.error('Bluetooth scan failed:', error);
    }
  }

  async connectToDevice(deviceId: string) {
    try {
      const device = await this.manager.connectToDevice(deviceId);
      console.log('Connected to:', device.name);
      return device;
    } catch (error) {
      console.error('Connection failed:', error);
      throw error;
    }
  }

  async disconnectDevice(deviceId: string) {
    try {
      await this.manager.cancelDeviceConnection(deviceId);
      console.log('Disconnected from device');
    } catch (error) {
      console.error('Disconnection failed:', error);
    }
  }
}

export default new BluetoothConnector();
